package org.vt.scheduleapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

public class LocationsActivity extends Activity {
	private LocWriter writer;
	private LocReader reader;
	private String locName;
	private double latitude;
	private double longitude;
	private List<Loc> locs;
	private Loc loc;
	private int count = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_location);

		final LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		final MyLocationListener mlocListener = new MyLocationListener();

		reader = new LocReader(this);
		try {
			locs = reader.getAllLocs();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// button1 allows the user to request the current location using the GPS
		// provider
		ImageButton button1 = (ImageButton) findViewById(R.id.button1);
		button1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// turns the stand alone gps on if it is not currently on
				if (!mlocManager
						.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
					final Intent poke = new Intent();
					poke.setClassName("com.android.settings",
							"com.android.settings.widget.SettingsAppWidgetProvider");
					poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
					poke.setData(Uri.parse("3"));
					sendBroadcast(poke);
				}
				mlocManager.requestLocationUpdates(
						LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
				//makeLoc();
			}
		});

		// button2 allows the user to request the current location using the
		// Network provider
		// if the user is connected to a network it uses that to find location
		// if the user is not connected it uses distances from closest cell
		// towers to find location
		ImageButton button2 = (ImageButton) findViewById(R.id.button2);
		button2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mlocManager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
				//makeLoc();
			}
			
		});

		ImageButton button3 = (ImageButton) findViewById(R.id.button3);
		button3.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent myIntent = new Intent(v.getContext(),
						LocLister.class);
				startActivityForResult(myIntent, 0);
			}
		});
		
		ImageButton button4 = (ImageButton) findViewById(R.id.button4);
		button4.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent myIntent = new Intent(v.getContext(),
						LocPlotter.class);
				startActivityForResult(myIntent, 0);
			}
		});
	}
	
	private void makeLoc()
	{
		
		writer = new LocWriter(this);
		AlertDialog.Builder alert = new AlertDialog.Builder(
				LocationsActivity.this);
		//while(latitude==0 || longitude ==0){}
		alert.setTitle("Please Enter a name for this location");
		alert.setMessage("Latitude: " + latitude + " Longitude: " + longitude);

		// Set an EditText view to get user input
		final EditText input = new EditText(LocationsActivity.this);
		alert.setView(input);

		alert.setPositiveButton("Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						Editable value = input.getText();
						locName = value.toString();
						loc = new Loc(locName, latitude, longitude);
						int compare;
						for(final Loc l: locs)
						{
							compare = loc.compare(l);
							if(compare==1)
							{
								count = 1;
								AlertDialog.Builder alert2 = new AlertDialog.Builder(
										LocationsActivity.this);
								alert2.setTitle("Error!");
								alert2.setMessage("A different Geographical location already has this name");

								// Set an EditText view to get user input
								final EditText input2 = new EditText(LocationsActivity.this);
								alert2.setView(input2);

								alert2.setPositiveButton("Change Name",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int whichButton) {
												Editable value2 = input2.getText();
												locName = value2.toString();
												loc.setName(locName);
												//add = 1;
												locs.add(loc);
												try {
													writer.writeLoc(locs);
												} catch (FileNotFoundException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												} catch (IOException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}
											}
								});
								alert2.setNegativeButton("Do not add this location",
										new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										}
								});
								alert2.show();
							}
							else if(compare==2)
							{
								count = 1;
								AlertDialog.Builder alert3 = new AlertDialog.Builder(
										LocationsActivity.this);
								alert3.setTitle("Error!");
								alert3.setMessage("This geographical location already exists with a differnt name");

								// Set an EditText view to get user input
								//final EditText input = new EditText(LocationsActivity.this);
								//alert3.setView(input);

								alert3.setPositiveButton("Use old name",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int whichButton) {
											}
								});
								alert3.setNegativeButton("Use new name",
										new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										l.setName(loc.getName());
										try {
											writer.writeLoc(locs);
										} catch (FileNotFoundException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										}
								});
								/*if(change == 1)
								{
									l.setName(loc.getName());
									change = 0;
								}*/
								
								alert3.show();
							}
							else if(compare==3)
							{
								count = 1;
								AlertDialog.Builder alert4 = new AlertDialog.Builder(
										LocationsActivity.this);
								alert4.setTitle("Notice!");
								alert4.setMessage("This location and name combination already exist");

								// Set an EditText view to get user input
								//final EditText input = new EditText(LocationsActivity.this);
								//alert4.setView(input);

								alert4.setPositiveButton("ok",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int whichButton) {
											}
								});
								alert4.show();
							}
								
						}
						if(count==0)
						{
							locs.add(loc);
							try {
								writer.writeLoc(locs);
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						
					}
				});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						// Canceled.
					}
				});
		alert.show();
	}

	public class MyLocationListener implements LocationListener {
		private double lat;
		private double lon;
		public void onLocationChanged(Location location) {
			while(lat == 0 || lon == 0)
			{
				lat = location.getLatitude();
				lon = location.getLongitude();
			}
			latitude=lat;
			longitude=lon;
			makeLoc();
		}

		// following three classes do not do anything but needed to be
		// implemented implemented
		public void onProviderDisabled(String provider) {

		}

		public void onProviderEnabled(String provider) {

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {

		}
	}
	@Override
	public void onBackPressed(){
		Intent myIntent = new Intent(this, Options.class);
		startActivityForResult(myIntent, 0);
	}

}
